package com.wuwei.elearning.question.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuwei.elearning.exception.ElearningMysqlException;
import com.wuwei.elearning.question.domain.*;
import com.wuwei.elearning.question.mapper.*;
import com.wuwei.elearning.question.service.QuestionItemService;
import com.wuwei.elearning.question.vo.GetResultVo;
import com.wuwei.elearning.question.vo.PageVo;
import com.wuwei.elearning.question.vo.QuestionVo;
import com.wuwei.elearning.question.vo.TestVo;
import com.wuwei.elearning.setting.domain.User;
import com.wuwei.elearning.setting.mapper.UserMapper;
import com.wuwei.elearning.utils.result.Result;
import com.wuwei.elearning.utils.token.TokenUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 每个单独的问题都会生成一个question_item 前端控制器
 * </p>
 *
 * @author wuwei
 * @since 2024-01-17
 */
@RestController
@RequestMapping("/elearning/questionItem")
@CrossOrigin
public class QuestionItemController {

    @Resource
    private HttpServletRequest request;

    @Resource
    private QuestionItemService questionItemService;

    @Resource
    private TestAnswersMapper testAnswersMapper;


    @Resource
    private QuestionMapper questionMapper;



    /**
     * 生成考题的方法
     * @return
     */
    @PostMapping("batchInsert")
    public Result<String> batchInsert(@RequestBody QuestionVo questionVo, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        List<String> chapters = questionVo.getChapter();
        Long subjectId = questionVo.getSubjectId();
        Integer number = questionVo.getNumber();
        Long gradeId = questionVo.getGradeId();
        Integer time = questionVo.getTime();
        return questionItemService.batchInsert(subjectId,chapters,number,gradeId,time,account,questionVo.getTitle());
    }





        /**
         * 考试获取考题的方法，每个考生只能考一遍，因此要先去查一下他有没有考过
         * @param questionItemId
         * @return
         */
    @GetMapping("batchGet/{data}")
    public Result<Map<String,Object>> batchGet(@PathVariable("data") Long questionItemId){
        //查询该考生是否已经考过一次了
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        return questionItemService.batchGet(questionItemId,account);

    }

    @GetMapping("getItem/{questionItemId}")
    public Result<Map<String,Object>> checkForTeacher(@PathVariable("questionItemId") Long questionItemId){
        return questionItemService.getItem(questionItemId);

    }

    @GetMapping("checkForStudent/{data}")
    public Result<Map<String,Object>> checkForStudent(@PathVariable("data") Long questionItemId){
        //查询该考生是否已经考过一次了
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        return questionItemService.checkForStudent(questionItemId,account);

    }

    /**
     * 考完提交试卷的方法
     * @param testVo
     * @return
     */
    @PostMapping("submit")
    public Result<String> submit (@RequestBody TestVo testVo){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        Result<String> result = questionItemService.submit(testVo,account);
        return result;
    }

    /**
     * 获取考卷的方法，此方法仅用于展示
     * @param questionItemId
     * @return
     */
    @GetMapping("getMyAnswers/{questionItemId}/{account}")
    public Result<List<List<String>>> getMyAnswers(@PathVariable("questionItemId") Long questionItemId,
                                                   @PathVariable("account") Long account){
        LambdaQueryWrapper<TestAnswers> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TestAnswers::getQuestionItemId,questionItemId).eq(TestAnswers::getUserId,account);
        List<TestAnswers> testAnswers = testAnswersMapper.selectList(queryWrapper);
        List<List<String>> result = testAnswers.stream().map(t -> {
            List<String> list = new ArrayList<>();
            for (int i = 0; i < 4; i++) {
                list.add("");
            }
            String selected = t.getSelected();
            if (selected == null) {
                return list;
            } else {
                String[] split = selected.split("\\+");
                for (int i = 0; i < split.length; i++) {
                    switch (split[i]) {
                        case "A":
                            list.set(0, split[i]);
                            break;
                        case "B":
                            list.set(1, split[i]);
                            break;
                        case "C":
                            list.set(2, split[i]);
                            break;
                        case "D":
                            list.set(3, split[i]);
                            break;
                        default:
                            System.out.println("其他");
                    }
                }
                return list;
            }
        }).collect(Collectors.toList());
        return Result.ok(result);
    }

    /**
     * 获取test_result表中的数据,并进行分页
     */
    @PostMapping("getResultList")
    public Result<List<QuestionItem>> getResultList(@RequestBody PageVo<GetResultVo> resultVoPageVo ) {
        List<QuestionItem> result = questionItemService.getResultList(resultVoPageVo);
        return Result.ok(result);
    }
    /**
     * 获取test_result表中的总数,并进行分页
     */
    @PostMapping("getResultTotal")
    public Result<Long> getResultTotal(@RequestBody GetResultVo resultVoPageVo ){
        Long result =questionItemService.getResultTotal(resultVoPageVo);
        return Result.ok(result);
    }

    /**
     * 删除question_item,question_item_raletion_question,test_answers,test_result四张表中有关记录
     * @param questionItemId
     * @return
     */
    @DeleteMapping("delete/{questionItemId}")
    public Result<String> delete (@PathVariable("questionItemId") Long questionItemId){
        //查询该考生是否已经考过一次了
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        return questionItemService.delete(questionItemId,account);
    }

    @PostMapping("batchDelete")
    public Result<String> batchDelete (@RequestBody List<QuestionItem> questionItems){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        return questionItemService.batchDelete(questionItems,account);
    }

    /**
     * 根据随堂练习的类型和科目获取相应的题目清单
     * @param type 支持的随堂练习有顺序练习，随机练习，错题练习，收藏练习
     * @param selectedId 如果小于10000，则为chapter表中的id字段，如果大于10000，则为subject表的id加上10000
     * @return
     */
    @GetMapping("getLearnItems/{type}/{selectedId}")
    public Result<List<Question>> getLearnItems(@PathVariable("type") String type, @PathVariable("selectedId") Long selectedId, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        List<Question> learnItems = questionItemService.getLearnItems(type, selectedId,account);
        return Result.ok(learnItems);
    }

    /**
     * 根据随堂练习的类型和科目获取相应的题目清单
     * @param question 问题的题目
     * @return
     */
    @GetMapping("getLearnItemsByQuestion/{question}")
    public Result<List<Question>> getLearnItemsByQuestion(@PathVariable("question") String question){
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        //这里搜索的时候不能搜索出DA42机型的题目
        queryWrapper.notLike(Question::getSubject,"DA42");
        queryWrapper.like(Question::getQuestion,question);
        List<Question> questions = questionMapper.selectList(queryWrapper);
        return Result.ok(questions);
    }

    @Resource
    private TokenUtil tokenUtil;

    @GetMapping("selectQuestionItems/{title}/{currentPage}/{pageSize}")
    public Result<Map<String,Object>> selectQuestionItems(HttpServletRequest request,@PathVariable("title") String title,
                                                          @PathVariable("currentPage") Integer currentPage, @PathVariable("pageSize") Integer pageSize
    ){
        String token = request.getHeader("Authorization");
        User user = tokenUtil.getUserFromToken(token);
        Map<String,Object> map = questionItemService.selectQuestionItems(title,user,currentPage,pageSize);
        return Result.ok(map);
    }

    /**
     * 查询该科目和该班级一共出了多少份试卷
     * @param subjectId
     * @param gradeId
     * @return
     */
    @GetMapping("getCount/{subjectId}/{gradeId}")
    public Result<Long> getCount(@PathVariable("subjectId")Long subjectId,@PathVariable("gradeId")Long gradeId){
        LambdaQueryWrapper<QuestionItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QuestionItem::getGradeId,gradeId).eq(QuestionItem::getSubjectId,subjectId);
        long count = questionItemService.count(queryWrapper);
        return Result.ok(count);
    }

    /**
     * 查询该学员还有多少道试卷未做
     * @param request
     * @return
     */
    @GetMapping("getCountByAccount")
    public Result<Integer> getCountByAccount(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        User user = tokenUtil.getUserFromToken(token);
        Integer count = questionItemService.getCountByAccount(user);
        return Result.ok(count);
    }


}

